package com.oim.fx.view.e;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.oim.core.business.box.PersonalBox;
<<<<<<< Updated upstream
<<<<<<< Updated upstream
import com.oim.core.business.manager.HeadImageManager;
=======
>>>>>>> Stashed changes
=======
>>>>>>> Stashed changes
import com.oim.core.business.manager.ImageManager;
import com.oim.core.business.sender.ChatSender;
import com.oim.core.business.sender.UserChatSender;
import com.oim.core.business.view.UserChatHistoryView;
import com.oim.core.common.action.BackAction;
import com.oim.core.common.action.BackInfo;
import com.oim.core.common.component.file.FileHandleInfo;
import com.oim.core.common.component.file.FileInfo;
import com.oim.fx.common.box.ImageBox;
import com.oim.fx.common.component.WaitingPane;
import com.oim.fx.common.util.ContentUtil;
import com.oim.fx.ui.chat.pane.MessageItemLeft;
import com.oim.fx.ui.chat.pane.MessageItemRight;
import com.oim.fx.ui.chat.pane.MessageList;
import com.only.common.lib.util.OnlyJsonUtil;
import com.only.common.result.Info;
import com.only.common.util.OnlyDateUtil;
import com.only.general.annotation.parameter.Define;
import com.only.net.action.Back;
import com.only.net.data.action.DataBackActionAdapter;
import com.onlyxiahui.app.base.AppContext;
import com.onlyxiahui.app.base.view.AbstractView;
import com.onlyxiahui.im.bean.UserData;
import com.onlyxiahui.im.message.data.chat.Content;
import com.onlyxiahui.im.message.data.chat.ImageValue;
import com.onlyxiahui.im.message.data.chat.Item;
import com.onlyxiahui.im.message.data.chat.Section;
import com.onlyxiahui.im.message.data.chat.history.UserChatHistoryData;
import com.onlyxiahui.im.message.data.query.ChatQuery;
import com.onlyxiahui.im.message.data.PageData;

import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.util.Callback;

/**
 * @author: XiaHui
 * @date: 2017年4月11日 下午12:07:41
 */
public class PaneUserChatHistoryViewImpl extends AbstractView implements UserChatHistoryView {

	PaneChatHistoryFrame frame;// = new ChatHistoryFrame();
	MessageList messageList;
	String userId;

	public PaneUserChatHistoryViewImpl(AppContext appContext) {
		super(appContext);
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				frame = new PaneChatHistoryFrame();
				messageList = frame.getMessageList();
				initEvent();
			}
		});
	}

	private void initEvent() {

		DataBackActionAdapter dataBackAction = new DataBackActionAdapter() {

			@Override
			public void lost() {
				showWaiting(true, WaitingPane.show_result);
			}

			@Override
			public void timeOut() {
				showWaiting(true, WaitingPane.show_result);
			}

			@Back
			public void back(Info info, @Define("sendUserId") String sendUserId, @Define("receiveUserId") String receiveUserId, @Define("contents") List<UserChatHistoryData> contents, @Define("page") PageData page) {
				setList(contents, page);
				showWaiting(false, WaitingPane.show_waiting);
			}
		};

		initPage();
		frame.setPageFactory(new Callback<Integer, Node>() {

			@Override
			public Node call(Integer index) {

				int pageNumber = (index + 1);
				PersonalBox pb = appContext.getBox(PersonalBox.class);
				UserData sendUser = pb.getUserData();
				PageData page = new PageData();
				page.setPageSize(30);
				page.setPageNumber(pageNumber);
				UserChatSender ds = appContext.getSender(UserChatSender.class);
				ds.queryUserChatLog(sendUser.getId(), (userId == null || "".equals(userId)) ? "00000" : userId, new ChatQuery(), page, dataBackAction);
				frame.showWaiting(true, WaitingPane.show_waiting);
				return new Label("第" + pageNumber + "页");
			}
		});
	}

	public void setList(List<UserChatHistoryData> contents, PageData page) {

		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				messageList.clearNode();
			}
		});

		if (null != contents) {
			for (UserChatHistoryData chd : contents) {
				UserData sendUserData = chd.getSendUserData();
				Content content = chd.getContent();
				String name = sendUserData.getNickname();
				String time = OnlyDateUtil.dateToDateTime(new Date(content.getTimestamp()));
				PersonalBox pb = appContext.getBox(PersonalBox.class);
				UserData user = pb.getUserData();
				boolean isOwn = user.getId().equals(sendUserData.getId());

				HeadImageManager him = appContext.getManager(HeadImageManager.class);
				String headPath = him.getUserHeadImagePath(sendUserData.getId(), 40);
				String orientation = isOwn ? "right" : "left";
				insertShow(messageList, name, headPath, time, orientation, content);
			}

		}
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				int totalPage = page.getTotalPage();
				frame.setTotalPage((totalPage <= 0 ? 1 : totalPage));
			}
		});
	}

	@Override
	public void setVisible(boolean visible) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				if (!isShowing()) {
					initPage();
				}
				if (visible) {
					frame.show();
					frame.toFront();
				} else {
					frame.hide();
				}
			}
		});
	}

	@Override
	public boolean isShowing() {
		return frame.isShowing();
	}

	public void showWaiting(boolean show, String key) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				frame.showWaiting(show, key);
			}
		});
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public void initPage() {
		frame.setPage(0, 10);
	}

	protected void insertShow(MessageList messageList, String name, String head, String time, String orientation, Content content) {
		if (null != messageList) {

			List<Item> items = ContentUtil.getImageItemList(content);
			if (!items.isEmpty()) {

				Map<String, Item> itemMap = new HashMap<String, Item>();
				for (Item item : items) {
					String imageInfo = item.getValue();
					if (null != imageInfo && !"".equals(imageInfo)) {
						if (OnlyJsonUtil.mayBeJSON(imageInfo)) {
							ImageValue iv = OnlyJsonUtil.jsonToObject(imageInfo, ImageValue.class);
							if (null != iv) {
								String id = iv.getId();
								itemMap.put(id, item);
							}
						}
					}
				}

				BackAction<List<FileHandleInfo>> backAction = new BackAction<List<FileHandleInfo>>() {

					@Override
					public void back(BackInfo backInfo, List<FileHandleInfo> list) {
						for (FileHandleInfo info : list) {
							FileInfo fi = info.getFileInfo();
							if (info.isSuccess()) {
								File file = (null != fi) ? fi.getFile() : null;
								String absolutePath = (null != file) ? file.getAbsolutePath() : null;
								String id = (null != fi) ? fi.getId() : "";
								Item item = itemMap.get(id);
								if (null != item && null != absolutePath) {
									item.setValue(absolutePath);
								}
							}
						}
						insertShowPane(messageList, name, head, time, orientation, content);
					}
				};
				ImageManager im = this.appContext.getManager(ImageManager.class);
				im.downloadImage(items, backAction);
			} else {
				insertShowPane(messageList, name, head, time, orientation, content);
			}
		}
	}

	protected void insertShowPane(MessageList messageList, String name, String head, String time, String orientation, Content content) {
		if (null != messageList) {

			Image headImage = ImageBox.getImagePath(head, 34, 34, 8, 8);

			boolean left = "left".equals(orientation);
			com.onlyxiahui.im.message.data.chat.Font f = content.getFont();
			Font font = Font.font(f.getName(), FontPosture.ITALIC, f.getSize());
			List<TextFlow> textFlowList = new ArrayList<TextFlow>();

			List<Section> sections = content.getSections();
			if (null != sections) {
				for (Section section : sections) {
					TextFlow textFlow = new TextFlow();

					List<Item> items = section.getItems();
					if (null != items) {
						for (Item item : items) {
							if (Item.type_text.equals(item.getType())) {
								String value = item.getValue();
								Text text = new Text(value);
								text.setFont(font);
								textFlow.getChildren().add(text);
							}
							if (Item.type_face.equals(item.getType())) {
								String faceInfo = item.getValue();
								if (StringUtils.isNotBlank(faceInfo)) {
									String[] array = faceInfo.split(",");
									if (array.length > 1) {
										String categoryId = array[0];
										String value = array[1];
										String fullPath = FaceUtil.getFacePath(categoryId, value);
										if (null != fullPath) {
											Image image = ImageBox.getImagePath(fullPath);
											textFlow.getChildren().add(new ImageView(image));
										}
									}
								}
							}
							if (Item.type_image.equals(item.getType())) {
								String imageInfo = item.getValue();
								if (StringUtils.isNotBlank(imageInfo)) {
									Image image = ImageBox.getImagePath(imageInfo);
									textFlow.getChildren().add(new ImageView(image));
								}
							}
						}
						textFlowList.add(textFlow);
					}
				}
			}
			Platform.runLater(new Runnable() {
				@Override
				public void run() {

					if (left) {
						MessageItemLeft mi = new MessageItemLeft();
						mi.setHeadImage(headImage);
						mi.setTimeText(time);
						mi.setName(name);

						for (TextFlow textFlow : textFlowList) {
							mi.addContentNode(textFlow);
						}
						messageList.addNode(mi);

					} else {
						MessageItemRight mi = new MessageItemRight();
						mi.setHeadImage(headImage);
						mi.setName(name);
						mi.setTimeText(time);
						for (TextFlow textFlow : textFlowList) {
							mi.addContentNode(textFlow);
						}
						messageList.addNode(mi);
					}
				}
			});
		}
	}
}
